//
//  UIImage+XY.m
//  ZhaoQiPei
//
//  Created by baiye on 2017/1/24.
//  Copyright © 2017年 XiangYun. All rights reserved.
//

#import "UIImage+XY.h"
#import "SDWebImageManager.h"

@implementation UIImage (XY)

+ (UIImage *)imageWithColor:(UIColor *)color {
    return [self imageWithColor:color size:CGSizeMake(1, 1)];
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (void)downloadImageWithURLString:(NSString *)URLString success:(void(^)(UIImage * image))success failure:(void(^)(NSError * error))failure {
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:URLString] options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (image) {
            if (success) {
                success(image);
            }
        }
        else {
            if (failure) {
                failure(error);
            }
        }
    }];
}

- (UIImage *)imageWithScale:(CGFloat)scale {
    CGSize size = CGSizeMake(self.size.width * scale, self.size.height * scale);
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image; // 返回的就是已经改变的图片
}

- (UIImage *)imageWithMaxSide:(CGFloat)side {
    if (IS_SCREEN_55_INCH) {
        side = side / 3;
    }
    else if (IS_SCREEN_47_INCH) {
        side = side / 2;
    }
    else if (IS_SCREEN_40_INCH) {
        side = side / 2;
    }
    CGFloat oldSide = self.size.width > self.size.height ? self.size.width : self.size.height;
    return [self imageWithScale:side/oldSide];
}

@end
